package cz.fabian.android.placeLocator;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class PlaceActivity extends Activity {
	private Float lat;
	private Float lon;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail);
        
        Bundle extras = getIntent().getExtras();
        long rowId = extras.getLong("rowId");
        
        DbAdapter helper = new DbAdapter(this);
        helper.open();
        Cursor place = helper.fetch(rowId);
        startManagingCursor(place);
        
        String latString = place.getString(place.getColumnIndexOrThrow(DbAdapter.KEY_LAT));
        String lonString = place.getString(place.getColumnIndexOrThrow(DbAdapter.KEY_LON));
        lat = Float.valueOf(latString);
        lon = Float.valueOf(lonString);
        
        TextView title = (TextView) findViewById(R.id.title);
        title.setText(place.getString(place.getColumnIndexOrThrow(DbAdapter.KEY_TITLE)));
        TextView coords = (TextView) findViewById(R.id.coords);
        coords.setText(latString + ", " + lonString);
        
        TextView distance = (TextView) findViewById(R.id.distance);
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        distance.setText(String.valueOf(
    		Helpers.formatDistance(Helpers.distFrom(
				lat, lon,
				Float.valueOf(String.valueOf(location.getLatitude())),
				Float.valueOf(String.valueOf(location.getLongitude()))
			)))
			+ " (" + getResources().getText(R.string.accuracy) + " " + location.getAccuracy() + " m)"
		);
    }
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
        menu.add(0, 1, 0, R.string.show_on_map);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case 1:
        	Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("geo:" + lat + "," + lon));
    		startActivity(i);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
}
